import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class UserMapperTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testCRUD() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);

            // Insert
            User user = new User();
            user.setUsername("John");
            user.setAge(30);
            mapper.insertUser(user);
            Assert.assertNotEquals(0, user.getId());

            // Select
            User selectedUser = mapper.selectUser(user.getId());
            Assert.assertEquals("John", selectedUser.getUsername());

            // Update
            selectedUser.setUsername("Jane");
            selectedUser.setAge(25);
            mapper.updateUser(selectedUser);

            // Select again
            User updatedUser = mapper.selectUser(selectedUser.getId());
            Assert.assertEquals("Jane", updatedUser.getUsername());

            // Delete
            mapper.deleteUser(updatedUser.getId());
            Assert.assertNull(mapper.selectUser(updatedUser.getId()));
        }
    }
}
